# AIQuant 量化投研系统 Makefile
# 提供便捷的开发、测试、部署命令

.PHONY: help install dev test lint format clean build deploy docker health

# 默认目标
.DEFAULT_GOAL := help

# 项目配置
PROJECT_NAME := aiquant
PYTHON := python3
PIP := pip3
DOCKER_REGISTRY := your-registry.com
DOCKER_NAMESPACE := aiquant
VERSION := $(shell grep -E '^version = ' pyproject.toml | cut -d'"' -f2)

# 颜色定义
RED := \033[31m
GREEN := \033[32m
YELLOW := \033[33m
BLUE := \033[34m
RESET := \033[0m

help: ## 显示帮助信息
	@echo "$(GREEN)AIQuant 量化投研系统 - 可用命令:$(RESET)"
	@echo ""
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "$(BLUE)%-20s$(RESET) %s\n", $$1, $$2}'
	@echo ""
	@echo "$(YELLOW)环境变量:$(RESET)"
	@echo "  PROJECT_NAME=$(PROJECT_NAME)"
	@echo "  VERSION=$(VERSION)"
	@echo "  PYTHON=$(PYTHON)"

# =============================================================================
# 环境设置
# =============================================================================

install: ## 安装项目依赖
	@echo "$(GREEN)安装项目依赖...$(RESET)"
	$(PIP) install -r requirements.txt
	$(PIP) install -r requirements-dev.txt
	@echo "$(GREEN)依赖安装完成$(RESET)"

install-dev: ## 安装开发环境依赖
	@echo "$(GREEN)安装开发环境依赖...$(RESET)"
	$(PIP) install -r requirements-dev.txt
	pre-commit install
	@echo "$(GREEN)开发环境设置完成$(RESET)"

venv: ## 创建虚拟环境
	@echo "$(GREEN)创建虚拟环境...$(RESET)"
	$(PYTHON) -m venv venv
	@echo "$(YELLOW)请运行: source venv/bin/activate$(RESET)"

# =============================================================================
# 开发命令
# =============================================================================

dev: ## 启动开发环境
	@echo "$(GREEN)启动开发环境...$(RESET)"
	$(PYTHON) scripts/start_system.py all --debug

api: ## 启动API服务器
	@echo "$(GREEN)启动API服务器...$(RESET)"
	$(PYTHON) scripts/start_system.py api --debug

web: ## 启动Web仪表板
	@echo "$(GREEN)启动Web仪表板...$(RESET)"
	$(PYTHON) scripts/start_system.py web

worker: ## 启动Celery工作进程
	@echo "$(GREEN)启动Celery工作进程...$(RESET)"
	$(PYTHON) scripts/start_system.py worker

beat: ## 启动Celery调度器
	@echo "$(GREEN)启动Celery调度器...$(RESET)"
	$(PYTHON) scripts/start_system.py beat

# =============================================================================
# 数据库管理
# =============================================================================

init-db: ## 初始化数据库
	@echo "$(GREEN)初始化数据库...$(RESET)"
	$(PYTHON) scripts/init_db.py

reset-db: ## 重置数据库（危险操作）
	@echo "$(RED)重置数据库...$(RESET)"
	@read -p "确定要重置数据库吗？这将删除所有数据 [y/N]: " confirm && [ "$$confirm" = "y" ]
	$(PYTHON) scripts/init_db.py --force

verify-db: ## 验证数据库状态
	@echo "$(GREEN)验证数据库状态...$(RESET)"
	$(PYTHON) scripts/init_db.py --verify-only

# =============================================================================
# 测试
# =============================================================================

test: ## 运行所有测试
	@echo "$(GREEN)运行测试...$(RESET)"
	pytest tests/ -v --cov=aiquant --cov-report=html --cov-report=term

test-unit: ## 运行单元测试
	@echo "$(GREEN)运行单元测试...$(RESET)"
	pytest tests/unit/ -v

test-integration: ## 运行集成测试
	@echo "$(GREEN)运行集成测试...$(RESET)"
	pytest tests/integration/ -v

test-api: ## 运行API测试
	@echo "$(GREEN)运行API测试...$(RESET)"
	pytest tests/test_api_endpoints.py -v

test-system: ## 运行系统集成测试
	@echo "$(GREEN)运行系统集成测试...$(RESET)"
	pytest tests/test_system_integration.py -v

test-coverage: ## 生成测试覆盖率报告
	@echo "$(GREEN)生成测试覆盖率报告...$(RESET)"
	pytest --cov=aiquant --cov-report=html --cov-report=term-missing
	@echo "$(YELLOW)覆盖率报告已生成: htmlcov/index.html$(RESET)"

# =============================================================================
# 代码质量
# =============================================================================

lint: ## 运行代码检查
	@echo "$(GREEN)运行代码检查...$(RESET)"
	flake8 aiquant/ tests/ scripts/
	mypy aiquant/
	bandit -r aiquant/

format: ## 格式化代码
	@echo "$(GREEN)格式化代码...$(RESET)"
	black aiquant/ tests/ scripts/
	isort aiquant/ tests/ scripts/

format-check: ## 检查代码格式
	@echo "$(GREEN)检查代码格式...$(RESET)"
	black --check aiquant/ tests/ scripts/
	isort --check-only aiquant/ tests/ scripts/

security: ## 安全检查
	@echo "$(GREEN)运行安全检查...$(RESET)"
	bandit -r aiquant/
	safety check

pre-commit: ## 运行pre-commit检查
	@echo "$(GREEN)运行pre-commit检查...$(RESET)"
	pre-commit run --all-files

# =============================================================================
# 健康检查和监控
# =============================================================================

health: ## 系统健康检查
	@echo "$(GREEN)系统健康检查...$(RESET)"
	$(PYTHON) scripts/health_check.py

health-json: ## 输出JSON格式的健康检查结果
	@echo "$(GREEN)系统健康检查（JSON格式）...$(RESET)"
	$(PYTHON) scripts/health_check.py --output json

health-monitor: ## 持续监控系统健康状态
	@echo "$(GREEN)启动持续监控...$(RESET)"
	$(PYTHON) scripts/health_check.py --continuous 30

status: ## 显示系统状态
	@echo "$(GREEN)系统状态:$(RESET)"
	$(PYTHON) scripts/start_system.py status

# =============================================================================
# 构建和打包
# =============================================================================

build: ## 构建项目
	@echo "$(GREEN)构建项目...$(RESET)"
	$(PYTHON) -m build

clean: ## 清理构建文件
	@echo "$(GREEN)清理构建文件...$(RESET)"
	rm -rf build/
	rm -rf dist/
	rm -rf *.egg-info/
	rm -rf .pytest_cache/
	rm -rf .coverage
	rm -rf htmlcov/
	find . -type d -name __pycache__ -exec rm -rf {} +
	find . -type f -name "*.pyc" -delete

docs: ## 生成文档
	@echo "$(GREEN)生成文档...$(RESET)"
	cd docs && mkdocs build

docs-serve: ## 启动文档服务器
	@echo "$(GREEN)启动文档服务器...$(RESET)"
	cd docs && mkdocs serve

# =============================================================================
# Docker相关
# =============================================================================

docker-build: ## 构建Docker镜像
	@echo "$(GREEN)构建Docker镜像...$(RESET)"
	docker build -t $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME):$(VERSION) .
	docker build -t $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME):latest .

docker-build-web: ## 构建Web Docker镜像
	@echo "$(GREEN)构建Web Docker镜像...$(RESET)"
	docker build -f deployment/docker/Dockerfile.web -t $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME)-web:$(VERSION) .
	docker build -f deployment/docker/Dockerfile.web -t $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME)-web:latest .

docker-push: ## 推送Docker镜像
	@echo "$(GREEN)推送Docker镜像...$(RESET)"
	docker push $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME):$(VERSION)
	docker push $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME):latest
	docker push $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME)-web:$(VERSION)
	docker push $(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(PROJECT_NAME)-web:latest

docker-run: ## 运行Docker容器
	@echo "$(GREEN)运行Docker容器...$(RESET)"
	docker-compose -f deployment/docker/docker-compose.yml up -d

docker-stop: ## 停止Docker容器
	@echo "$(GREEN)停止Docker容器...$(RESET)"
	docker-compose -f deployment/docker/docker-compose.yml down

docker-logs: ## 查看Docker日志
	@echo "$(GREEN)查看Docker日志...$(RESET)"
	docker-compose -f deployment/docker/docker-compose.yml logs -f

docker-clean: ## 清理Docker资源
	@echo "$(GREEN)清理Docker资源...$(RESET)"
	docker system prune -f
	docker volume prune -f

# =============================================================================
# 生产部署
# =============================================================================

deploy-dev: ## 部署到开发环境
	@echo "$(GREEN)部署到开发环境...$(RESET)"
	docker-compose -f deployment/docker/docker-compose.yml up -d

deploy-prod: ## 部署到生产环境
	@echo "$(GREEN)部署到生产环境...$(RESET)"
	docker-compose -f deployment/docker/docker-compose.prod.yml up -d

k8s-deploy: ## 部署到Kubernetes
	@echo "$(GREEN)部署到Kubernetes...$(RESET)"
	kubectl apply -f deployment/k8s/

k8s-delete: ## 从Kubernetes删除
	@echo "$(GREEN)从Kubernetes删除...$(RESET)"
	kubectl delete -f deployment/k8s/

# =============================================================================
# 数据和备份
# =============================================================================

backup: ## 备份数据
	@echo "$(GREEN)备份数据...$(RESET)"
	mkdir -p backups
	pg_dump $(DATABASE_URL) > backups/backup_$(shell date +%Y%m%d_%H%M%S).sql
	@echo "$(GREEN)备份完成$(RESET)"

restore: ## 恢复数据（需要指定备份文件）
	@echo "$(GREEN)恢复数据...$(RESET)"
	@if [ -z "$(BACKUP_FILE)" ]; then \
		echo "$(RED)请指定备份文件: make restore BACKUP_FILE=backup.sql$(RESET)"; \
		exit 1; \
	fi
	psql $(DATABASE_URL) < $(BACKUP_FILE)
	@echo "$(GREEN)数据恢复完成$(RESET)"

# =============================================================================
# 监控和日志
# =============================================================================

logs: ## 查看应用日志
	@echo "$(GREEN)查看应用日志...$(RESET)"
	tail -f logs/aiquant.log

logs-error: ## 查看错误日志
	@echo "$(GREEN)查看错误日志...$(RESET)"
	tail -f logs/error.log

monitor: ## 启动监控
	@echo "$(GREEN)启动监控...$(RESET)"
	docker-compose -f monitoring/docker-compose.yml up -d

monitor-stop: ## 停止监控
	@echo "$(GREEN)停止监控...$(RESET)"
	docker-compose -f monitoring/docker-compose.yml down

# =============================================================================
# 实用工具
# =============================================================================

shell: ## 启动Python shell
	@echo "$(GREEN)启动Python shell...$(RESET)"
	$(PYTHON) -c "import sys; sys.path.insert(0, '.'); from aiquant.config.settings import get_settings; print('AIQuant shell ready. Settings loaded.'); import IPython; IPython.start_ipython()"

notebook: ## 启动Jupyter Notebook
	@echo "$(GREEN)启动Jupyter Notebook...$(RESET)"
	jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root

requirements: ## 更新requirements.txt
	@echo "$(GREEN)更新requirements.txt...$(RESET)"
	pip freeze > requirements.txt

check-deps: ## 检查依赖更新
	@echo "$(GREEN)检查依赖更新...$(RESET)"
	pip list --outdated

update-deps: ## 更新依赖
	@echo "$(GREEN)更新依赖...$(RESET)"
	pip install --upgrade -r requirements.txt

# =============================================================================
# 开发工具
# =============================================================================

profile: ## 性能分析
	@echo "$(GREEN)运行性能分析...$(RESET)"
	$(PYTHON) -m cProfile -o profile.stats -m aiquant.main
	$(PYTHON) -c "import pstats; p = pstats.Stats('profile.stats'); p.sort_stats('cumulative').print_stats(20)"

memory-profile: ## 内存分析
	@echo "$(GREEN)运行内存分析...$(RESET)"
	mprof run $(PYTHON) -m aiquant.main
	mprof plot

benchmark: ## 运行基准测试
	@echo "$(GREEN)运行基准测试...$(RESET)"
	$(PYTHON) -m pytest benchmarks/ -v

# =============================================================================
# 版本管理
# =============================================================================

version: ## 显示版本信息
	@echo "$(GREEN)版本信息:$(RESET)"
	@echo "  项目版本: $(VERSION)"
	@echo "  Python版本: $(shell $(PYTHON) --version)"
	@echo "  Git版本: $(shell git describe --tags --always --dirty 2>/dev/null || echo 'unknown')"

tag: ## 创建版本标签
	@echo "$(GREEN)创建版本标签...$(RESET)"
	git tag -a v$(VERSION) -m "Release version $(VERSION)"
	git push origin v$(VERSION)

release: ## 发布新版本
	@echo "$(GREEN)发布新版本...$(RESET)"
	$(MAKE) test
	$(MAKE) lint
	$(MAKE) build
	$(MAKE) tag
	@echo "$(GREEN)版本 $(VERSION) 发布完成$(RESET)"

# =============================================================================
# 特殊目标
# =============================================================================

all: install lint test build ## 执行完整的CI流程

ci: ## CI流程
	@echo "$(GREEN)执行CI流程...$(RESET)"
	$(MAKE) install-dev
	$(MAKE) lint
	$(MAKE) test-coverage
	$(MAKE) security
	$(MAKE) build

setup: ## 初始化项目环境
	@echo "$(GREEN)初始化项目环境...$(RESET)"
	$(MAKE) install
	$(MAKE) init-db
	@echo "$(GREEN)项目环境初始化完成$(RESET)"
	@echo "$(YELLOW)现在可以运行: make dev$(RESET)"

# 检查必要的工具
check-tools:
	@command -v $(PYTHON) >/dev/null 2>&1 || { echo "$(RED)Python3 未安装$(RESET)"; exit 1; }
	@command -v docker >/dev/null 2>&1 || { echo "$(YELLOW)Docker 未安装，Docker相关命令将不可用$(RESET)"; }
	@command -v kubectl >/dev/null 2>&1 || { echo "$(YELLOW)kubectl 未安装，Kubernetes相关命令将不可用$(RESET)"; }

# 在所有目标前检查工具
%: check-tools
	@: